<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>小米搜索框-关键字高亮</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    ul {
      list-style: none;
    }
    .mi {
      position: relative;
      width: 223px;
      margin: 100px auto;
    }
    .mi input {
      width: 223px;
      height: 48px;
      padding: 0 10px;
      font-size: 14px;
      line-height: 48px;
      border: 1px solid #e0e0e0;
      outline: none;
    }
    .mi .search {
      border: 1px solid #ff6700;
    }
    .result-list {
      display: none;
      position: absolute;
      left: 0;
      top: 48px;
      width: 223px;
      border: 1px solid #ff6700;
      border-top: 0;
      background: #fff;
    }
    .result-list a {
      display: block;
      padding: 6px 15px;
      font-size: 12px;
      color: #424242;
      text-decoration: none;
    }
    .result-list a:hover {
      background-color: #eee;
    }
  </style>

</head>

<body>
  <div class="mi">
    <input type="search" placeholder="小米笔记本">
    <ul class="result-list">
      <!-- <li><a href="#">全部商品</a></li> -->
    </ul>
  </div>
  <script>
    const data = [
      '全部商品', '小米11', '小米10S',
      '小米笔记本', '小米手机', '黑鲨4', '空调'
    ]
    const input = document.querySelector('input')
    const result = document.querySelector('.result-list')
  
    input.addEventListener('blur', function() {
      result.style.display = 'none'
      this.classList.remove('search')
    })

    input.addEventListener('input', function() {
      result.style.display = 'block'
      this.classList.add('search')
      render(this.value)
    })

    function render(value) {
      const htmlStr = data.map(item => {
        return `<li><a href="#">${handlerKeywords(item, value)}</a></li>`
      }).join('')
      result.innerHTML = htmlStr
    }

    function handlerKeywords(item, value) {
      if (!value) return item
      const reg = new RegExp(value, 'g')
      return item.replace(reg, `<span style='color: red'>${value}</span> `)
    }
  </script>
</body>

</html>
